<template>
  <div class="login">
    <b-row class="mt-5">
      <b-col md="8" offset-md="2" lg="6" offset-lg="3">
        <b-card title="登录" class="text-left">
          <b-form>
            <b-form-group label="用户名">
              <b-form-input
                v-model="$v.user.name.$model"
                type="text"
                placeholder="输入您的用户名"
              ></b-form-input>
              <b-form-invalid-feedback :state="validateState('name')">
                用户名应不小于5位且不大于20位
              </b-form-invalid-feedback>        
            </b-form-group>
  
            <b-form-group label="密码">
              <b-form-input
                v-model="$v.user.password.$model"
                type="password"
                placeholder="输入您的密码"
                :state="validateState('password')"
              ></b-form-input>
              <b-form-invalid-feedback :state="validateState('password')">
                密码需大于等于6位小于等于20位
              </b-form-invalid-feedback>  
            </b-form-group>
  
            <b-form-group>
              <b-button 
                variant="outline-primary" 
                @click="login"
                block>
                登录
              </b-button>
            </b-form-group>

          </b-form>
        </b-card>
      </b-col>
    </b-row>
  </div>
</template>
  
  <script>
  import { required, minLength, maxLength } from 'vuelidate/lib/validators'
  import { mapActions } from 'vuex'
  import customValidator from '@/helper/validator.js'
  export default {
    data() {
      return {
        user: {
          name: '',
          password:'',
        },
      }
    },
    validations: {
      user: {
        name : {
          required,
          minLength : minLength(5),
          maxLength : maxLength(20),
        },
        password : {
          required,
          minLength : minLength(6),
          maxLength : maxLength(20),
        }
      }
    },
    methods: {
      ...mapActions('userModule', { userLogin: 'login'}),
      validateState(name) {
        const { $dirty, $error } = this.$v.user[name]
        return $dirty? !$error : null
      },
      login() {
        //验证数据
        this.$v.user.$touch()
        if (this.$v.user.$anyError) {
          return ;
        }
        //请求
        this.userLogin(this.user).then(() => {
          this.$router.replace({name: 'home'})
        }).catch((err) => {
          //console.log(err)
          this.$bvToast.toast(err.response.data.msg, {
            title: '数据验证错误',
            variant: 'danger',
            solid: true,
          })
        })
      }
    }
  }
</script>
  
<style lang="scss" scoped>
  
</style>